document.addEventListener('DOMContentLoaded', () =>{
    initForm();
    initErrorHandling();
})

function initForm(){
    const selectForm = document.querySelector('.form-group-select');
    const inputUsername = document.getElementById('form-input-username');
    const inputPassword = document.getElementById('form-input-password');

    const initialRole = selectForm.value;
    if(initialRole === '0'){
        inputUsername.name = 'sno';
        inputUsername.placeholder = '请输入学号';
    } else {
        inputUsername.name = 'username';
        inputUsername.placeholder = '请输入用户名';
    }

    selectForm.addEventListener('change', (e) => {
        const selectedValue = e.target.value;
        if(selectedValue == '0'){
            inputUsername.name = 'sno';
            inputUsername.placeholder = '请输入学号';
        }else{
            inputUsername.name = 'username';
            inputUsername.placeholder = '请输入用户名';
        }

        // 清除用户名字段的错误状态
        clearFieldError(inputUsername);
    })
}

function initErrorHandling() {
    // 为有错误的字段添加错误状态类
    const errorFields = document.querySelectorAll('.field-error');
    errorFields.forEach(errorDiv => {
        const formGroup = errorDiv.closest('.form-group');
        if (formGroup) {
            formGroup.classList.add('has-error');
        }
    });

    // 为输入框添加焦点事件，清除错误状态
    const inputs = document.querySelectorAll('input, select');
    inputs.forEach(input => {
        input.addEventListener('focus', () => {
            clearFieldError(input);
        });
    });
}

function clearFieldError(input) {
    const formGroup = input.closest('.form-group');
    if (formGroup) {
        formGroup.classList.remove('has-error');
        const errorDiv = formGroup.querySelector('.field-error');
        if (errorDiv) {
            errorDiv.style.animation = 'slideOutUp 0.3s ease';
            setTimeout(() => {
                errorDiv.remove();
            }, 300);
        }
    }
}